/**
 * 
 */
package com.huniu.analysis.dictionary.tree.model;

import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zandy (chenheng)
 * 
 */
public class TreeNode implements Node {
	private Node parent;
	private ValuePair pair;
	private Map<ValuePair,Node> children;
	private boolean isEndNode;
	
	public TreeNode() {
		this.parent = null ;
		this.pair = null ;
		this.children = null ;
		this.isEndNode = false ;
	}
	
	public TreeNode(String value) {
		ValuePair pair = new ValuePair(value);
		this.parent = null ;
		this.pair = pair ;
		this.children = null ;
		this.isEndNode = false ;
	}
	
	public TreeNode(ValuePair pair) {
		this.parent = null ;
		this.pair = pair ;
		this.children = null ;
		this.isEndNode = false ;
	}
	
	public TreeNode(Node parent,ValuePair pair,boolean isEndNode) {
		this.parent = parent ;
		this.pair = pair ;
		this.children = null ;
		this.isEndNode = isEndNode ;
	}
	
	public Node getParent() {
		return parent;
	}

	public void setParent(Node parent) {
		this.parent = parent;
	}

	public ValuePair getPair() {
		return pair;
	}

	public void setPair(ValuePair pair) {
		this.pair = pair;
	}

	public Map<ValuePair,Node> getChildren() {
		return children;
	}

	public void addChild(ValuePair pair, Node child) {
		if ( children == null ) {
			children = new HashMap<ValuePair,Node>();
		}
		children.put(pair, child);
	}

	public void removeChild(Node child) {
		children.remove(child);
	}

	public boolean isEndNode() {
		return isEndNode;
	}

	public void setEndNode(boolean isEndNode) {
		this.isEndNode = isEndNode;
	}
	
	public int hashCode() {
		int hash = 7 ;
		int weight = (pair == null ? 0 : pair.hashCode());
		hash = 31 * hash + weight ;
		return hash ;
	}
	
	public boolean equals(Object obj) {
		if ( this == obj ) {
			return true ;
		}
		if ( obj == null || ( obj.getClass() != this.getClass() )) {
			return false ;
		}
		TreeNode treeNode = ( TreeNode ) obj;
		if ( this.pair == treeNode.pair || ( this.pair != null && this.pair.equals(treeNode.pair) )) {
			return true ;
		}
		return false ;
	}

	public void readExternal(ObjectInput in) throws IOException,
			ClassNotFoundException {
		this.isEndNode = in.readBoolean();
		this.pair = (ValuePair) in.readObject();
	}

	public void writeExternal(ObjectOutput out) throws IOException {
		out.writeBoolean(this.isEndNode);
		out.writeObject(this.getPair());
	}
}
